package com.bookhouse.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.bookhouse.dao.BaseDAO;
import com.bookhouse.dao.DAOException;
import com.bookhouse.dao.ReaderDAO;
import com.bookhouse.domain.Reader;
import com.bookhouse.util.HibernateSessionFactory;

public class ReaderDAOImpl extends BaseDAO implements ReaderDAO {

	@Override
	public void insert(Reader reader) throws DAOException {
		Transaction tx = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.save(reader);
			tx.commit();
		} catch (Exception ex) {
			throw new DAOException("Error adding reader. " + ex.getMessage());
		} finally {
			if (tx != null)
				tx = null;
			HibernateSessionFactory.closeSession();
		}

	}

	@Override
	public List<Reader> getReader() throws DAOException {
		List<Reader> list = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			String hql = "from Reader";
			list = session.createQuery(hql).list();
		} catch (Exception ex) {
			throw new DAOException("Error getting reader. " + ex.getMessage());
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return list;
	}

	@Override
	public Reader getReader(int id) throws DAOException {
		Reader reader = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			reader = (Reader) session.get(Reader.class, id);
		} catch (Exception ex) {
			throw new DAOException("Error getting reader. " + ex.getMessage());
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return reader;
	}

	@Override
	public void updateReader(Reader reader) throws DAOException {
		Transaction tx = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.update(reader);
			tx.commit();
		} catch (Exception ex) {
			throw new DAOException("Error updating reader. " + ex.getMessage());
		} finally {
			if (tx != null)
				tx = null;
			HibernateSessionFactory.closeSession();
		}

	}

	@Override
	public void deleteReader(int id) throws DAOException {
		Transaction tx = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Reader reader = (Reader) session.get(Reader.class, id);
			session.delete(reader);
			tx.commit();
		} catch (Exception ex) {
			throw new DAOException("Error deleting reader. " + ex.getMessage());
		} finally {
			if (tx != null)
				tx = null;
			HibernateSessionFactory.closeSession();
		}

	}

	@Override
	public void deleteAllReader() throws DAOException {
		// TODO Auto-generated method stub

	}

}
